var app = getApp();

Page({
  data: {
    gender: 0, // 性别
    date: '', // 出生日期
    formatDate: undefined,
    height: undefined, // 身高
    weight: undefined, // 体重
    illnessDuration: undefined, // 患病时长
    bloodSugarUnit: 'mmol/L', // 偏好的血糖单位，默认值
    dateVisible: false,
    second: undefined, // 使用自定义函数格式化当前时间
    activeGender: '',
    activeUnit: '',
  },

  selectGender(e) {
    const gender = e.currentTarget.dataset.gender;
    this.setData({
      activeGender: gender // 新增字段来跟踪当前激活的性别,
    });

    const genderValue = gender === 'male' ? 1 : gender === 'female' ? 2 : null;

    // 更新性别并设置激活按钮
    this.setData({
      gender: genderValue,
    });
  },

  showPicker(e) {
    const {
      mode
    } = e.currentTarget.dataset; // 从事件对象中获取模式值
    this.setData({
      mode,
      [`${mode}Visible`]: true,
    });
  },

  hidePicker() {
    const {
      mode
    } = this.data;
    this.setData({
      [`${mode}Visible`]: false,
    });
  },
  onConfirm(e) {
    const {
      value
    } = e?.detail;
    const {
      mode
    } = this.data;
    this.setData({
      [mode]: value,
    });
    this.hidePicker();
  },
  onColumnChange(e) {
    console.log('pick', e?.detail?.value);
  },

  // 处理输入
  onInput(e) {
    const {
      value
    } = e.detail;
    const {
      field
    } = e.currentTarget.dataset; // 使用 data-field 属性

    // 将输入的字符串转换为浮点数
    const numericValue = parseFloat(value);

    this.setData({
      [field]: numericValue, // 更新为浮点数
    });
  },

  // 选择血糖单位
  selectBloodSugarUnit(e) {
    const unit = e.currentTarget.dataset.unit;
    this.setData({
      bloodSugarUnit: unit,
      activeUnit: unit
    });
  },

  // 提交信息
  onSubmit() {
    this.setData({
      formatDate: Math.floor(new Date(this.data.date).getTime() / 1000)
    });

    const {
      gender,
      date,
      formatDate,
      height,
      weight,
      illnessDuration,
      bloodSugarUnit,
    } = this.data;

    // 表单验证
    if (!gender) {
      wx.showToast({
        title: '请选择性别',
        icon: 'none'
      });
      return;
    }
    if (!date) {
      wx.showToast({
        title: '请选择出生日期',
        icon: 'none'
      });
      return;
    }
    if (!height) {
      wx.showToast({
        title: '请填写身高',
        icon: 'none'
      });
      return;
    }
    if (!weight) {
      wx.showToast({
        title: '请填写体重',
        icon: 'none'
      });
      return;
    }
    if (!illnessDuration) {
      wx.showToast({
        title: '请填写患病时长',
        icon: 'none'
      });
      return;
    }

    // 获取用户信息
    const username = wx.getStorageSync('userInfo').username;
    // 打印提交信息
    console.log('提交信息:', {
      username: username, // 获取用户名
      gender,
      formatDate,
      height,
      weight,
      illnessDuration,
      bloodSugarUnit,
    });

    wx.request({
      url: `${app.globalData.protocol}://${app.globalData.host}/bgmp/api/user?Action=UpdateUserInfo`,
      method: 'POST',
      header: {
        "Content-Type": "application/json",
        "x-api-key": wx.getStorageSync('token'),
      },
      data: {
        "username": username, // 将用户名作为参数传入
        "avatar": "",
        "gender": gender,
        "birthday": formatDate,
        "height": height,
        "weight": weight,
        "illness_duration": illnessDuration,
        "glucose_unit": bloodSugarUnit,
      },
      success: (res) => {
        // 处理成功响应
        if (res.statusCode == 200) {
          wx.switchTab({
            url: '/pages/foodrecord/foodrecord',
          });
        } else {
          console.log(res.data.message)
          console.log("upload unsuccessfully");
        }
      },
      fail: (err) => {
        // 处理错误
        console.log(err)
        console.log("upload unsuccessfully");
      }
    });
  },
  fail: (err) => {
    wx.showToast({
      title: '获取用户信息失败',
      icon: 'none'
    });
    console.error('获取用户信息失败:', err);
  }
});

function formatDate(date) {
  var year = date.getFullYear();
  var month = padZero(date.getMonth() + 1); //月份是从0开始的
  var day = padZero(date.getDate());
  return year + '-' + month + '-' + day;
}

// // 自定义函数，格式化日期时间
// function formatTime(date) {
//   var hours = date.getHours();
//   var minutes = padZero(date.getMinutes());
//   // var seconds = padZero(date.getSeconds());
//   // console.log(date)
//   return hours + ':' + minutes;
// }

// // 自定义函数，补零
// function padZero(num) {
//   return (num < 10 ? '0' : '') + num;
// }